<template>
	<view>
		<view>
			<view>
				<view class='header'>
					<image src='../../static/images/logo.png'></image>
				</view>
				<view class='content'>
					<view>校友录将申请获取以下权限</view>
					<text>您的公开信息(昵称，头像、位置等信息)</text>
				</view>
				<!-- withCredentials=true  获取到除用户基本信息之外的encryptedData以及iv等数据 -->
				<button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="wxGetUserInfo">
					授权登录
				</button>

			</view>
		</view>
	</view>
</template>

<script>
	let app = getApp();
	import {
		mapState,
		mapMutations
	} from 'vuex'
	
	export default {
		onLoad() {
			//this.login()
		},
		computed: {
			...mapState(['openid'])
		},
		methods: {
			...mapMutations(['setUser','setOpenid']),
			wxGetUserInfo() {
				let that = this;
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log("登录", loginRes);
						var params = {
							url: 'users/getOpenid',
							type: 'POST',
							data: {
								code: loginRes.code
							},
							sCallback: function(res) {
								console.log('res:' + res);
								that.setOpenid(res);
								that.wxlogin(res);	
							}
						}
						app.request(params);						
						uni.hideLoading();
					},
				})
			},
			wxlogin: function(openid) {
				let that = this;
				let params = {
					url: 'users/wxlogin',
					type: 'POST',
					data: {
						openid: openid
					},
					sCallback: function(res) {
						if (res.token != "-1") {
							that.userInfo = res.user;
							that.userInfo["token"] = res.token;							
							that.setUser(that.userInfo);
																		
							uni.reLaunch({
								url: '/pages/home/home'
							});	
						} else {
							uni.getUserInfo({
								provider: 'weixin',
								success: function(infoRes) {
									console.log('infoRes:', infoRes);
									that.userInfo = infoRes.userInfo;
									that.userInfo["id"] = 0;
									that.userInfo["username"] = "访客";
									that.userInfo["token"] = res.token;	
									that.userInfo["wxNickName"] = "0";	
									that.setUser(that.userInfo);
																													
									uni.reLaunch({
										url: '/pages/register/register'
									});	
								}
							});
						}
					}
				}
				app.request(params);
			}
		}
	}
</script>

<style scoped>
	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 300rpx;
		line-height: 450rpx;
	}

	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
		background-color: #255BBA;
	}
</style>
